package myJs.components

import japgolly.scalajs.react._
import japgolly.scalajs.react.component.Scala.BackendScope
import japgolly.scalajs.react.extra.StateSnapshot
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.myPkg.MiniColorsOptions
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.html

import scala.scalajs.js
import scala.scalajs.js.UndefOr

/**
 * Created by yz on 3/11/2020
 */
object PureMiniColorComponent {

  case class Props(state: StateSnapshot[String], name: String) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  class Backend(bs: BackendScope[Props, Unit]) {

    private val inputRef = Ref[html.Input]

    def didMount(p: Props) = {

      def mcVChange(value: String) = {
        val myValue = value
        p.state.modState { state =>
          myValue
        }.unsafeRunSync()
      }

      def colorChange = (value: js.UndefOr[String], opacity: js.UndefOr[js.Any]) => {
        mcVChange(value.get)
        if (opacity.isDefined) {
          s"${value.get},${opacity.get}"
        } else {
          value.get
        }
      }

      val s = p.state.value
      inputRef.foreach { y =>
        val swatches = List("#00ff00", "#FFFFFF", "#a5d6a7", "#fff59d",
          "#ffcc80", "#bcaaa4", "#eeeeee", "#f44336", "#2196f3", "#4caf50", "#ffeb3b", "#ff9800", "#795548", "#9e9e9e")
        val options = MiniColorsOptions(
          control = "hue",
          format = "hex",
          swatches = swatches,
          theme = "bootstrap",
          inline = false,
          letterCase = "lowercase",
          position = "bottom",
          keywords = "",
          change = colorChange,
          opacity = false,
          defaultValue = s
        )
        $(y).minicolors(options)
      }
    }

    def didUpdate(p: Props) = {
      inputRef.foreach { y =>
        $(y).minicolors("value", js.Dictionary("color" -> s"${$(y).myVal}"))
      }
    }

    def unmount = {
      inputRef.foreach { y =>
      }
    }

    def render(p: Props) = {

      def valueChange(e: ReactEventFromInput) = {
        val myValue = e.target.value
        p.state.modState(x => myValue)
      }

      val s = p.state.value
      input(`type` := "text", `class` := "form-control", name := s"${p.name}", value := s"${s}",
        onChange ==> valueChange).withRef(inputRef)
    }

  }

  val Component = ScalaComponent.builder[Props].renderBackend[Backend].
    componentDidMount(x => x.backend.didMount(x.props)).componentDidUpdate(x => x.backend.didUpdate(x.currentProps)).
    componentWillUnmount(_.backend.unmount).
    build

}



